package com.alliky.user.ui.viewmodel;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.alliky.core.base.viewmodel.ToolbarViewModel;
import com.alliky.core.binding.command.BindingCommand;
import com.alliky.core.bus.RxMessager;
import com.alliky.core.bus.SingleLiveEvent;
import com.alliky.core.data.DataRepository;
import com.alliky.core.entity.vo.GoodsVO;
import com.alliky.core.entity.vo.UserVO;
import com.alliky.core.global.Global;
import com.alliky.core.net.IDisposableObserver;
import com.alliky.core.util.RxUtils;
import com.alliky.core.util.StringUtils;
import com.alliky.user.BR;
import com.alliky.user.R;
import com.alliky.user.ui.activity.LoginActivity;
import com.alliky.user.ui.activity.PersonCenterActivity;
import com.alliky.user.ui.activity.SettingActivity;

import java.util.List;
import java.util.WeakHashMap;

import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * @Description TODO
 * @Author wxianing
 * @Date 2020-11-15
 */
public class MyViewModel extends ToolbarViewModel<DataRepository> {

    //退出登录
    public final static String KEY_LOGOUT = "key_logout";
    //登录成功
    public final static String KEY_LOGIN_SUCCESS = "key_login_success";

    public ObservableField<String> username = new ObservableField<>("未登录");
    public ObservableField<String> nickname = new ObservableField<>("");
    public ObservableField<Boolean> nicknameVisable = new ObservableField<>(false);

    UserVO mUserVO = null;

    public MyViewModel(@NonNull Application application) {
        super(application);
        mUserVO = Global.UserManage.getUser();
        if (mUserVO != null) {
            username.set(mUserVO.getUsername());
            nickname.set(mUserVO.getNickname());
            nicknameVisable.set(true);
        }

        //登录成功
        RxMessager.getDefault().register(this, KEY_LOGIN_SUCCESS, String.class, message -> {
            mUserVO = Global.UserManage.getUser();
            if (mUserVO != null) {
                username.set(mUserVO.getUsername());
                nickname.set(mUserVO.getNickname());
                nicknameVisable.set(true);
            }
        });

        //退出登录
        RxMessager.getDefault().register(this, KEY_LOGOUT, String.class, message -> {
            username.set("未登录");
            nickname.set("");
            nicknameVisable.set(false);
        });
    }

    public void initToolbar() {
        setBackIconVisible(View.GONE);
        setRightIconVisible(View.VISIBLE);
        setRightIcon(ContextCompat.getDrawable(getApplication(), R.mipmap.icon_setting));
        setTitleText("我的");
    }

    @Override
    protected void rightIconOnClick() {
        super.rightIconOnClick();
        startActivity(SettingActivity.class);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefresh = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadMore = new SingleLiveEvent<>();
    }

    public ObservableList<RecommendItemViewModel> obserableRecommendList = new ObservableArrayList<>();

    public ItemBinding<RecommendItemViewModel> mItemBinding = ItemBinding.of(BR.viewModel, R.layout.item_user_recommend_layout);

    public BindingCommand onPersonCenter = new BindingCommand(() -> {
        String token = Global.UserManage.getToken();
        if (StringUtils.isBlank(token)) {
            startActivity(LoginActivity.class);
        } else {
            startActivity(PersonCenterActivity.class);
        }
    });

    public BindingCommand onLogin = new BindingCommand(() -> {
        String token = Global.UserManage.getToken();
        if (StringUtils.isBlank(token)) {
            startActivity(LoginActivity.class);
        }
    });

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(() -> {
        pageNum = 1;
        getRecommendGoods();
    });
    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(() -> {
        pageNum++;
        getRecommendGoods();
    });

    public void initData() {
        getRecommendGoods();
    }

    public void getRecommendGoods() {
        WeakHashMap<String, Object> param = new WeakHashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        mRepository.getRecommendGoods(param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))// 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())// 线程调度
                .compose(RxUtils.exceptionTransformer())// 网络错误的异常转换
                .doOnSubscribe(this)
                .subscribe(new IDisposableObserver<List<GoodsVO>>() {
                    @Override
                    protected void onResult(List<GoodsVO> goodsVOS) {
                        if (pageNum == 1) {
                            obserableRecommendList.clear();
                            uc.finishRefresh.call();
                        } else {
                            uc.finishLoadMore.call();
                        }

                        for (GoodsVO goodsVO : goodsVOS) {
                            RecommendItemViewModel viewModel = new RecommendItemViewModel(MyViewModel.this, goodsVO);
                            obserableRecommendList.add(viewModel);
                        }
                    }
                });

    }
}
